package py.com.alfa.escriba.gui.controller;

import java.io.Serializable;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.context.WebApplicationContext;
import org.thymeleaf.TemplateEngine;
import org.winter.dialect.response.JsonResponse;
import org.winter.utils.command.AjaxResponse;
import org.winter.utils.command.ControllerObject;

import py.com.alfa.escriba.gui.controller.object.admin.DatosComplementariosControllerObject;
import py.com.alfa.escriba.gui.controller.view.View;
import py.com.alfa.escriba.gui.controller.view.ViewManager;
import py.com.alfa.escriba.gui.dto.gestion.DatoscomplementariosDTO;
import py.com.alfa.escriba.gui.rest.services.DatosComplService;
import py.com.alfa.escriba.gui.services.HelperService;
import py.com.alfa.escriba.gui.services.TabRef;
import py.com.alfa.escriba.gui.session.SystemInfo;
import py.com.alfa.escriba.gui.spring.processors.SpringBean;
import py.com.alfa.escriba.gui.utils.ObjectUtils;
import py.com.sif.rest.client.spring.exception.RestClientException;

@Controller
@Scope("session")
@SessionAttributes("datosComp")
@RequestMapping("/datosComp")
public class DatosComplementariosController implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 2130343223176809591L;
	private final static String PAGE_NAME = "pag:datosComp";
	private final static String CONTROLLER_OBJECT_NAME = "datosComp";
	
	private Logger log = LoggerFactory.getLogger(getClass());
	@SpringBean private SystemInfo systemInfo;
	@SpringBean private ViewManager viewManager;
	@SpringBean private HelperService helperService;
	@SpringBean private DatosComplService datosComplService;
	
	@Autowired
	private WebApplicationContext wac;
	
	@Autowired
	private TemplateEngine templateEngine;
	@ControllerObject	
	private DatosComplementariosControllerObject datosComp;
	private Locale locale;
	
	
	public DatosComplementariosController() {
		this.loadObjects();
	}

	private void loadObjects() {
		setLocale(LocaleContextHolder.getLocale());
	}

	private String verifAuto() {
		Subject subject = SecurityUtils.getSubject();
		if (subject == null || !subject.isAuthenticated()) {
			return "redirect:/";
		}		
		Boolean permitted = subject.isPermitted(DatosComplementariosController.PAGE_NAME);
		systemInfo.setSystemError(false);
		if (!permitted) {
			systemInfo.setSystemError(true);
			systemInfo.setErrorMessage("El usuario no esta autorizado para utilizar este recurso");
			return "error";
		}
		return null;
	}

	
	@ModelAttribute(CONTROLLER_OBJECT_NAME)
	public DatosComplementariosControllerObject getDatosComp() {
		return datosComp;
	}

	public void setDatosComp(DatosComplementariosControllerObject datosComp) {
		this.datosComp = datosComp;
	}

	public Locale getLocale() {
		return locale;
	}

	public void setLocale(Locale locale) {
		this.locale = locale;
	}
	
	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String homePage(Model model, HttpServletRequest request, HttpServletResponse response) {
		this.log.info("datos complementarios!");
		try {
			this.getDatosComp().view().disableAll();
			String auto = this.verifAuto();
			if ( auto != null ) {
				return auto;
			}
			loadObject();
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
		}
		return View.DATOSCOMP;
	}
	
	private void loadObject(){
		try {
			
			this.getDatosComp().setDatos(this.datosComplService.listDatoscomplementarios());
			this.getDatosComp().setTipos(this.helperService.getTablaRef(TabRef.TIPO_DATO));
			this.getDatosComp().view().enable().lista();
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
		}
	}

	@RequestMapping(value = "/agregarDato", method = RequestMethod.POST)
	public @ResponseBody JsonResponse agregarDato(Model model, HttpServletRequest request, HttpServletResponse response, 
			@AjaxResponse(View.DATOSCOMP) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) DatosComplementariosControllerObject datosComp, BindingResult bindingResult) {
		this.log.info("DatosComplementarios - Nuevo!");
		
		try {
			this.getDatosComp().setDato(new DatoscomplementariosDTO());
			this.getDatosComp().getDato().setUsaListaDeValores(false);
			this.getDatosComp().getDato().setActivo(true);
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
			return jResponse.error(e.getMessage());
		}
		
		this.getDatosComp().view().disableAll().enable().datoComp();
		return jResponse.success(request, response, wac, model, templateEngine);
	}
	
	@RequestMapping(value = "/usaLvEvent", method = RequestMethod.POST)
	public @ResponseBody JsonResponse usaLvEvent(Model model, HttpServletRequest request, HttpServletResponse response, 
	       @AjaxResponse(View.DATOCOMP) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) DatosComplementariosControllerObject datosComp, BindingResult bindingResult) {
		
		try {
			this.log.info("INDICADOR LISTA DE VALOR EVENT! {}", this.getDatosComp().getDato().getUsaListaDeValores());		
			this.getDatosComp().getDato().setListadevalor(null);
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
	       
	    return jResponse.success(request, response, wac, model, templateEngine);
	  }
	
	@RequestMapping(value = "/consultar", method = RequestMethod.POST)
	public @ResponseBody JsonResponse consultar(Model model, HttpServletRequest request, HttpServletResponse response, 
		@AjaxResponse(View.DATOSCOMP) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) DatosComplementariosControllerObject datosComp, BindingResult bindingResult) {
		this.log.info("vehiculos - consultar! {}");
		try {
			this.getDatosComp().setDatos(this.datosComplService.listDatoscomplementarios());
			this.getDatosComp().view().disableAll().enable().lista();
			jResponse.setView(View.DATOSCOMP);
			} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		return jResponse.success(request, response, wac, model, templateEngine);
	}
	
	@RequestMapping(value = "/guardarDatoComp", method = RequestMethod.POST)
	public @ResponseBody JsonResponse guardarDatoComp(Model model, HttpServletRequest request, HttpServletResponse response, 
			@AjaxResponse(View.DATOCOMP) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) DatosComplementariosControllerObject datosComp, BindingResult bindingResult){
		this.log.info("GUARDAR DATOCOMP!");
		try {
			
			DatoscomplementariosDTO obj = this.getDatosComp().getDato();			
			this.log.info("DATOCOMP:{}", obj);
			
			if ( obj.getId() == null ) {
				this.datosComplService.createDatoscomplementarios(obj);
			} else {
				this.datosComplService.saveDatoscomplementarios(obj);
			}
			this.getDatosComp().setDatos(this.datosComplService.listDatoscomplementarios());
			this.getDatosComp().setDato(null);
			this.getDatosComp().setDatoOri(null);
			this.getDatosComp().view().disableAll().enable().lista();
			jResponse.setView(View.DATOSCOMP);
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
			return jResponse.error(e.getMessage());
		}
		
		return jResponse.success(request, response, wac, model, templateEngine);
	}
	

	@RequestMapping(value = "/editarDatoComp/{index}", method = RequestMethod.POST)
	public @ResponseBody JsonResponse editarDatoComp(Model model,HttpServletRequest request, HttpServletResponse response, 
			@AjaxResponse(View.DATOSCOMP) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) DatosComplementariosControllerObject datosComp, BindingResult bindingResult, 
		         @PathVariable("index") String ind) {
		this.log.info("\n============== EDITAR DATOCOMP! {}\n==============\n", ind);
		try {
			Integer index = Integer.parseInt(ind);
			DatoscomplementariosDTO obj = this.getDatosComp().getDatos().get(index);
			this.log.info("DATOCOMP: {}", obj);
			DatoscomplementariosDTO datoComp = this.datosComplService.showDatoscomplementarios(obj.getId());
			datoComp.setTipoDato(this.helperService.getTablaRef(TabRef.TIPO_DATO, datoComp.getIdtipodato()));
			this.getDatosComp().setDato(datoComp);		
			this.getDatosComp().setDatoOri(new DatoscomplementariosDTO());
			ObjectUtils.copyValues(datoComp, this.getDatosComp().getDatoOri());
			this.getDatosComp().getDatos().remove(obj);
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		this.getDatosComp().view().disableAll().enable().datoComp();
		return jResponse.success(request, response, wac, model, templateEngine);
	}

	@RequestMapping(value = "/deleteDatoComp/{index}", method = RequestMethod.POST)
	public @ResponseBody JsonResponse deleteDatoComp(Model model,HttpServletRequest request, HttpServletResponse response, 
			@AjaxResponse(View.DATOSCOMP) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) DatosComplementariosControllerObject datosComp, BindingResult bindingResult, 
		         @PathVariable("index") String ind) {
		this.log.info("\n==============\nELIMINANDO DATOCOMP! {}\n==============\n", ind);
		try {
			Integer index = Integer.parseInt(ind);
			DatoscomplementariosDTO obj = this.getDatosComp().getDatos().get(index);
			this.log.info("DATOCOMP: {}", obj);
			if ( obj.getId() != null ) {
				this.datosComplService.deleteDatoscomplementarios(obj.getId());
			}
			this.getDatosComp().getDatos().remove(obj);
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		return jResponse.success(request, response, wac, model, templateEngine);
	}
	
	@RequestMapping(value = "/cancelar", method = RequestMethod.POST)
	public @ResponseBody JsonResponse cancelar(Model model, HttpServletRequest request, HttpServletResponse response, 
		@AjaxResponse(View.DATOSCOMP) JsonResponse jResponse, @ModelAttribute(CONTROLLER_OBJECT_NAME) DatosComplementariosControllerObject datosComp, BindingResult bindingResult) {
		this.log.info("\n==============\nCancelar!\n==============\n");
		try {
			this.getDatosComp().setDato(null);
		    this.getDatosComp().view().disableAll().enable().lista();
		    
			this.getDatosComp().setDato(null);
			this.getDatosComp().setDatos(this.datosComplService.listDatoscomplementarios());
			this.getDatosComp().view().datosComp().enable();
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			if (e.getCause() != null && e.getCause() instanceof RestClientException) {
				return jResponse.error(e.getCause().getMessage());
			}
		}
		return jResponse.success(request, response, wac, model, templateEngine);
	}
	
}	

